import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Binary extends JFrame implements ActionListener {
    private JComboBox<String> comboBox_name;
    private JComboBox<String> opCombo;
    private Button eql;
    private TextField a,b,c,d,ans,ans1;
    @Override
    public void actionPerformed(ActionEvent e) {
        Integer num3 = Integer.parseInt(a.getText());
        String num33 = Integer.toBinaryString(num3);
        this.c.setText(num33);
        Integer num4 = Integer.parseInt(b.getText());
        String num44 = Integer.toBinaryString(num4);
        this.d.setText(num44);
        try {
            // 获取输入数值和运算符
            Integer num1 = Integer.parseInt(a.getText());
            Integer num2 = Integer.parseInt(b.getText());
            String operator = "";
            int result = 0;
            switch (opCombo.getSelectedIndex()) {
                case 0:  // 位与
                    result = num1 & num2;
                    break;
                case 1:  // 位或
                    result = num1 | num2;
                    break;
                case 2:  // 位异或
                    result = num1 ^ num2;
                    break;
                default:
                    break;
            }
            this.ans.setText(Integer.toString(result));
            this.ans1.setText(Integer.toBinaryString(result));
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Invalid input", "Error", JOptionPane.ERROR_MESSAGE);
        } catch (ArithmeticException ex) {
            JOptionPane.showMessageDialog(this, "Divide by zero", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    public Binary(){
        super("二进制运算");
        //关闭窗口
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //表格长宽
        this.setSize(500,200);
        //表格的位置
        this.setLocationRelativeTo(null);
        //表格框架
        this.setLayout(new GridLayout(3,3,10,10));
        this.add(new TextField());
        //第一个文本行
        this.add(this.a = new TextField("0",10));
        //2
        this.add(this.c = new TextField("0",10));
        // 创建单选按钮显示并选择运算符
        opCombo = new JComboBox<>(new String[]{"&", "|", "^"});
        this.add(opCombo);
        //第二个文本行
        this.add(this.b = new TextField("0",10));
        this.add(this.d = new TextField("0",10));
        //"="按钮
        this.eql = new Button("=");
        this.add(this.eql);
        this.eql.addActionListener(this);
        this.add(this.ans = new TextField(10));
        this.add(this.ans1 = new TextField(10));
        //可视化
        this.setVisible(true);
    }
    public static void main(String[] args) {
        new Binary();
    }
}
